<template>
  <el-dialog title="编辑销项发票" :visible.sync="dialogVisible" width="1600px" :close-on-click-modal="false"
    :modal-append-to-body="false" v-drag2anywhere>
    <el-form :model="formData" ref="formData" label-width="100px" size="mini" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="3">
          <el-form-item label="状态">
            <el-select v-model="formData.status">
              <el-option label="正常" value="1"></el-option>
              <el-option label="作废" value="0"></el-option>
              <el-option label="红冲" value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="发票类型:" prop="type">
            <el-select v-model="formData.type">
              <el-option label="增值税普票" value="增值税普票"></el-option>
              <el-option label="增值税专票" value="增值税专票"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="开票日期:" prop="date">
            <el-date-picker type="datetime" value-format="yyyy-MM-dd H:m:s" placeholder="开票日期" style="width: 100%;"
              v-model="formData.date"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发票号码" prop="fphm">
            <el-input v-model="formData.fphm" placeholder="数电票号码或纸质发票号码" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发票代码" prop="fpdm" >
            <el-input v-model="formData.fpdm" placeholder="发票代码" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="购方单位:" prop="buyer">
            <el-select v-model="formData.buyer" style="width: 100%;" filterable clearable @change="handleBuyerChanged">
              <el-option v-for="(item,index) in buyerlist" :label="item.title" :value="item.title" :key="index">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="所属账套:" prop="seller">
              <el-select v-model="formData.seller" style="width: 100%;" filterable clearable @change="handleSellerChanged">
                <el-option v-for="(item,index) in sellerlist" :label="item.name" :value="item.name" :key="index">
                </el-option>
              </el-select>
            </el-form-item>
        </el-col>

      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item >
            <div style="font-size: 12px; color: #888888;">
              <div>【税号】:{{formData.buyer_taxid}}</div>
              <div>【地址及电话】：{{formData.buyer_address}} {{formData.buyer_mobile}}</div>
              <div>【开户行及账号】:{{formData.buyer_bank}} {{formData.buyer_cardnum}}</div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item >
            <div style="font-size: 12px; color: #888888;">
              <div>【税号】:{{formData.seller_taxid}}</div>
              <div>【地址及电话】：{{formData.seller_address}} {{formData.seller_mobile}}</div>
              <div>【开户行及账号】:{{formData.seller_bank}} {{formData.seller_cardnum}}</div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col>
          <el-form-item label="发票明细:">
            <div style="display: flex;">
              <div style="flex: 1;">标 <span style="color:#FF0000">*</span> 字段为必填项</div>
              <div>
                <el-button-group>
                  <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增货物</el-button>
                  <el-button type="primary" icon="el-icon-finished" size="mini" @click="handleBuyTicketFilter">选择进项
                  </el-button>
                </el-button-group>
              </div>
            </div>
            <div class="tablewraper">
              <el-table :data="formData.goods" border style="width: 100%;" height="100%">
                <el-table-column label="序号" type="index" align="center" width="50px"></el-table-column>
                <el-table-column label="稅收类目" width="180px">
                  <template v-slot="scope">
                    <el-select filterable v-model="scope.row.taxname" clearable
                      @change="handleTaxClassifyChanged(scope.$index,scope.row)">
                      <el-option v-for="(item,index) in taxclassify" :key="index" :label="item.name" :value="item.name">
                        <div style="width: 500px;display: flex;" :title="item.keyword">
                          <div style="flex: 1;">{{item.name}}</div>
                          <span style="color:#d1d1d1;font-size: 12px;"> {{item.keyword}}</span>
                        </div>
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="货物或应税劳务、服务名称">
                  <template slot="header">
                    <span style="color:#FF0000">*</span> 货物或应税劳务、服务名称
                  </template>
                  <template v-slot="scope">
                    <el-input v-model="scope.row.title" type="textarea" :rows="1" placeholder="货物名称"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="规格型号" width="120px">
                  <template v-slot="scope">
                    <el-input v-model="scope.row.model" type="textarea" :rows="1" placeholder="型号"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="单位" align="center" width="90px">
                  <template v-slot="scope">
                    <el-input v-model="scope.row.unit" placeholder="单位"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="数量" align="center" width="95px">
                  <template slot="header">
                    <span style="color:#FF0000">*</span> 数量
                  </template>
                  <template v-slot="scope">
                    <el-input v-model="scope.row.count" @change="handleCountChange(scope.$index,scope.row)"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="单价" align="center" width="120px" show-overflow-tooltip>
                  <template v-slot="scope">
                    {{scope.row.price}}
                  </template>
                </el-table-column>
                <el-table-column label="金额" align="center" prop="total" width="150px">
                  <template slot="header">
                    <span style="color:#FF0000">*</span> 金额
                  </template>
                  <template v-slot="scope">
                    <el-input-number v-model="scope.row.total" size="mini" style="width: 100%;" :step="0.001"
                      :precision="3" @change="handleTotalChange(scope.$index,scope.row)"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="税率" prop="rate" width="100px" align="center">
                  <template v-slot="scope">
                    <el-select v-model="scope.row.rate" placeholder="请选择税率"
                      @change="handleRateChange(scope.$index,scope.row)">
                      <el-option label="免税" value="0"></el-option>
                      <el-option label="1%" value="0.01"></el-option>
                      <el-option label="1.5%" value="0.15"></el-option>
                      <el-option label="3%" value="0.03"></el-option>
                      <el-option label="5%" value="0.05"></el-option>
                      <el-option label="6%" value="0.06"></el-option>
                      <el-option label="9%" value="0.09"></el-option>
                      <el-option label="12%" value="0.12"></el-option>
                      <el-option label="13%" value="0.13"></el-option>
                      <el-option label="16%" value="0.16"></el-option>
                      <el-option label="17%" value="0.17"></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="税额" align="center" prop="tax" width="145px">
                  <template slot="header">
                    <span style="color:#FF0000">*</span> 税额
                  </template>
                  <template v-slot="scope">
                    <el-input-number v-model="scope.row.tax" size="mini" style="width: 100%;" :step="0.01"
                      :precision="3" @change="handleTotalChange(scope.$index,scope.row)"></el-input-number>
                  </template>
                </el-table-column>
                <el-table-column label="价税总额" align="center" prop="total" width="130px">
                  <template slot="header">
                    <span style="color:#FF0000">*</span> 金额(含税)
                  </template>
                  <template v-slot="scope">
                    {{parseFloat(scope.row.sum).toFixed(3)}}
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="60px" fixed="right">
                  <template v-slot="scope">
                    <el-button circle icon="el-icon-delete" type="danger" @click="handleDelete(scope.$index,scope.row)">
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div>
              <div style="float: right; margin:5px;">
                <span style="margin-right:15px">记录数: {{formData.goods.length}}</span>
                <span style="margin-right:15px">金额: {{formData.total}}</span>
                <span style="margin-right:15px">税额: {{formData.tax}}</span>
                <span style="margin-right:15px">合计: {{formData.sum}}</span>
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="发票附件:" prop="attach">
            <el-upload list-type="picture-card" ref="upload" :file-list="upconfig.imgList" :action="upconfig.action"
              :headers="upconfig.headers" :accept="upconfig.accept" :limit="upconfig.limit" :on-change="handleChange"
              :auto-upload="false" :on-remove="handleRemove" :on-exceed="handleLimit" multiple
              :on-preview="handlePreview">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="备注" prop="memo">
            <el-input type="textarea" :rows="4" v-model="formData.memo" maxlength="255" show-word-limit
              placeholder="备注信息"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>

    <BuyDetailFilterUI v-if="buyFilterVisible" ref="buyFilterUI" @completeHandler="handleFilterSelect">
    </BuyDetailFilterUI>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false" size="medium">取 消</el-button>
      <el-button type="primary" size="medium" @click="handleSave">提交申请</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import BuyDetailFilterUI from './buyticketfilter.vue';
  import NewClientUI from './newclient.vue';
  export default {
    components: {
      BuyDetailFilterUI,
      NewClientUI
    },
    data() {
      return {
        index:-1,
        sellerlist: [],
        buyerlist: [],
        taxclassify: [],
        formData: {
          fpdm: '',
          type: '增值税专票',
          fphm: '',
          date: '',
          buyer: '',
          total: 0,
          tax: 0,
          sum: 0,
          goods: [],
          memo: '',
        },
        buylist: [],
        clients: [],
        dialogVisible: false,
        buyFilterVisible: false,
        //文件上传相关变量
        upconfig: {
          //文件上传相关参数
          accept: '.jpg,.jpeg,.png,.pdf',
          limit: 5,
          headers: {
            token: localStorage.getItem('token') != null ? localStorage.getItem('token') : ''
          },
          imgList: [],
          fileList: [],
          rids: [], //要删除的id
          action: ""
        },
        rules: {
          fphm: [{
            required: true,
            message: '请正确填写发票号码!',
            trigger: 'blur'
          }],
          buyer: [{
            required: true,
            message: '请正确填写购买方名称!',
            trigger: 'blur'
          }],
          date: [{
            required: true,
            message: '请正确填写开票时间!',
            trigger: 'blur'
          }],
          type: [{
            required: true,
            message: '请选择发票类型!',
            trigger: 'change'
          }],
          seller: [{
            required: true,
            message: '请填定销售企业名称!',
            trigger: 'blur'
          }],
          buyer: [{
            required: true,
            message: '请填写购买企业名称!',
            trigger: 'blur'
          }]
        },
      }
    },
    mounted() {
      this.loadSellerList();
      this.loadBuyerList();
    },
    methods: {
      init(index,data) {
        this.index=index;
        this.formData=data;
        this.upconfig.imgList=data.attach;
        this.upconfig.fileList=[];
        this.loadTaxClasasify();
        this.handleRefreshBottomSum();
      },
      loadBuyerList() {
        this.axios.post("api/admin/client/list_op").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.buyerlist = res.data.list;
          }
        });
      },
      loadSellerList() {
        this.axios.post("api/admin/supplier/list_item").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.sellerlist = res.data.list;
          }
        });
      },
      handleBuyerChanged(title) {
        var option = this.buyerlist.filter(function(cur, index, a) {
          if (cur.title == title) {
            return cur;
          }
        })[0];
        if(option){
          this.formData.buyer = option.title;
          this.formData.buyer_taxid = option.taxcode;
          this.formData.buyer_address = option.address;
          this.formData.buyer_mobile = option.mobile;
          this.formData.buyer_bank = option.bankname;
          this.formData.buyer_cardnum = option.bankid;
        }else{
          this.formData.buyer=  this.formData.buyer_taxid=this.formData.buyer_address =this.formData.buyer_mobile=this.formData.buyer_bank=this.formData.buyer_cardnum=""
        }
      },

      handleSellerChanged(seller){
        var option = this.sellerlist.filter(function(cur, index, a) {
          if (cur.name == seller) {
            return cur;
          }
        })[0];
        if(option){
        this.formData.seller = option.name;
        this.formData.seller_taxid = option.socialcode;
        this.formData.seller_address = option.address;
        this.formData.seller_mobile = option.telephone;
        this.formData.seller_bank = option.bankname;
        this.formData.seller_cardnum = option.cardnumber;
        }else{
          this.formData.seller=  this.formData.seller_taxid=this.formData.seller_address =this.formData.seller_mobile=this.formData.seller_bank=this.formData.seller_cardnum=""

        }
      },
      handleBuyTicketFilter() {
        this.buyFilterVisible = true;
        this.$nextTick(() => {
          this.$refs.buyFilterUI.dialogVisible = true;
          this.$refs.buyFilterUI.initData();
        })
      },
      checkArrayObjectValueRepeat(dataArr, key, value) {
        let valArr = [],
          check = '';
        dataArr.some(item => {
          if (valArr.includes(item[key])) return check = '不能重复';
          valArr.push(item[key]);
          return false;
        })
        return check;
      },
      handleFilterSelect(goods) {
        for (var i = 0; i < goods.length; i++) {
          var result = this.formData.goods.some(item => item.did === goods[i].id);
          if (!result) {
            let ngoods = {
              id: -1,
              title: goods[i].title,
              model: goods[i].model,
              unit: goods[i].unit,
              count: parseFloat(goods[i].count),
              price: parseFloat(goods[i].price),
              total: parseFloat(goods[i].total),
              taxcode: goods[i].taxcode,
              taxname: goods[i].taxname,
              rate: goods[i].rate,
              sum: parseFloat(goods[i].sum),
              tax: parseFloat(goods[i].tax),
              fphm: goods[i].num,
              fpdm:goods[i].code
            }
            this.formData.goods.push(ngoods);
          }
        }
        this.handleRefreshBottomSum();
      },

      handleTotalChange(index, data) {
        this.formData.goods[index].price = parseFloat(this.formData.goods[index].total) / parseFloat(this.formData
          .goods[index].count);
        this.formData.goods[index].sum = parseFloat(parseFloat(this.formData.goods[index].total) + parseFloat(this
          .formData.goods[index].tax)).toFixed(3);
        //this.formData.goods[index].tax=this.format2Number(this.formData.goods[index].total*parseFloat(this.formData.goods[index].rate),3);
        this.handleRefreshBottomSum();
      },
      handleTaxChange(index, data) {
        this.formData.goods[index].price = parseFloat(this.formData.goods[index].total) / parseFloat(this.formData
          .goods[index].count);
        this.formData.goods[index].sum = parseFloat(parseFloat(this.formData.goods[index].total) + parseFloat(this
          .formData.goods[index].tax)).toFixed(3);
        //this.formData.goods[index].tax=this.format2Number(this.formData.goods[index].total*parseFloat(this.formData.goods[index].rate),3);
        this.handleRefreshBottomSum();
      },
      handleCountChange(index, data) {
        this.formData.goods[index].price = parseFloat(this.formData.goods[index].total) / parseFloat(this.formData
          .goods[index].count);
        this.formData.goods[index].sum = parseFloat(parseFloat(this.formData.goods[index].total) + parseFloat(this
          .formData.goods[index].tax)).toFixed(3);
        this.handleRefreshBottomSum();
      },
      handleRateChange(index, row) {
        this.formData.goods[index].price = parseFloat(this.formData.goods[index].total) / parseFloat(this.formData
          .goods[index].count);
        this.formData.goods[index].sum = parseFloat(parseFloat(this.formData.goods[index].total) + parseFloat(this
          .formData.goods[index].tax)).toFixed(3);
        this.handleRefreshBottomSum();
      },
      handleRefreshBottomSum() {
        this.formData.sum = 0;
        this.formData.tax = 0;
        this.formData.total = 0;
        this.formData.goods.forEach((item) => {
          this.formData.total += parseFloat(item.total);
          this.formData.sum += parseFloat(item.sum);
          this.formData.tax += parseFloat(item.tax);
          console.log(item.total);
        })
        this.formData.sum = parseFloat(this.formData.sum).toFixed(3);
        this.formData.tax = parseFloat(this.formData.tax).toFixed(3);
        this.formData.total = parseFloat(this.formData.total).toFixed(3);
      },
      handleSupnameChanged(title) {
        var option = this.supplierList.filter(function(cur, index, a) {
          if (cur.title == title) {
            return cur;
          }
        })[0];
        this.formData.bankname = option.bankname;
        this.formData.banknumber = option.banknumber;
      },
      /***********************文件上传区域开始****************/
      //文件数量超限提示
      handleLimit: function() {
        this.$message.warning("最多可上传" + this.upconfig.limit + "个文件");
      },
      handleChange: function(file, list) {
        //判断文件格式和数量
        var ext = file.name.substr(file.name.lastIndexOf('.') + 1).toLowerCase();
        var extarr = ['jpg', 'jpeg', 'png', "pdf"];
        var sizeok = file.size / 1024 / 1024 < 5;
        if (extarr.lastIndexOf(ext) == -1) {
          this.$message.error("上传文件格式必须为" + extarr.join(","));
          //删除刚上传的文件
          this.upconfig.fileList.splice(this.upconfig.fileList.length - 1, 1);
          return;
        }
        if (!sizeok) {
          this.$message.error("上传文件大小最大不超过5M");
          this.upconfig.fileList.splice(this.upconfig.fileList.length - 1, 1);
          return;
        }

        this.upconfig.fileList = list;
      },
      // 文件列表移除文件时的钩子
      handleRemove: function(file, fileList) {
        if (file.id) { //如果存储id即为已经上传好的图片
          this.upconfig.rids.push(file.id);
        }
        this.upconfig.fileList = fileList;
      },
      /***********************文件上传区域结束****************/

      handleTaxClassifyChanged(index, data) {
        var option = this.taxclassify.filter(function(cur, index, a) {
          if (cur.name == data.taxname) {
            return cur;
          }
        })[0];
        this.formData.goods[index].taxname = option.name;
        this.formData.goods[index].taxcode = option.code;
      },
      format2Number(value, len) {
        var f = parseFloat(value);
        return parseFloat(f.toFixed(parseInt(len)));
      },


      loadTaxClasasify() {
        this.axios.post("api/common/taxclassify/list").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.taxclassify = res.data.list;
          }
        });
      },
      handlePreview(file) {
        console.log("yulan");
      },
      handleSave() {
        this.$refs.formData.validate(ok => {
          if (ok) {
            //检测物品信息
            let index = 1;
            let verifyOk = true;
            for (var i = 0; i < this.formData.goods.length; i++) {
              index = (i + 1);
              if (this.formData.goods[i].taxcode == "") {
                this.$message.error({
                  message: '第' + index + "行 请选择相应的税收分类!",
                  duration: 1500,
                  showClose: true
                });
                verifyOk = false;
                break;
              } else if (this.formData.goods[i].title == "") {
                this.$message.error({
                  message: '第' + index + "行 货物或应税劳务、服务名称填写有误!",
                  duration: 1500,
                  showClose: true
                });
                verifyOk = false;
                break;
              } else if (this.formData.goods[i].count == "" || this.formData.goods[i].count == "") {
                this.$message.error({
                  message: '第' + index + "行 采购数量填写不正确!",
                  duration: 1500,
                  showClose: true
                });
                verifyOk = false;
                break;
              } else if (parseFloat(this.formData.goods[i].sum) == 0) {
                this.$message.error({
                  message: '第' + index + "行 含税总额填写不正确!",
                  duration: 1500,
                  showClose: true
                });
                verifyOk = false;
                break;
              }
            }

            if (!verifyOk) {
              return;
            }

            //提交
            var fd = new FormData();
            fd.append("id",this.formData.id);
            fd.append("status",this.formData.status);
            fd.append("buyer", this.formData.buyer);
            fd.append("buyer_taxid",this.formData.buyer_taxid);
            fd.append("buyer_address",this.formData.buyer_address);
            fd.append("buyer_mobile",this.formData.buyer_mobile);
            fd.append("buyer_bank",this.formData.buyer_bank);
            fd.append("buyer_cardnum",this.formData.buyer_cardnum);
            fd.append("seller", this.formData.seller);
            fd.append("seller_taxid",this.formData.seller_taxid);
            fd.append("seller_address",this.formData.seller_address);
            fd.append("seller_mobile",this.formData.seller_mobile);
            fd.append("seller_bank",this.formData.seller_bank);
            fd.append("seller_cardnum",this.formData.seller_cardnum);
            fd.append("fphm",this.formData.fphm);
            fd.append("type", this.formData.type);
            fd.append("date", this.formData.date);
            fd.append("fpdm", this.formData.fpdm);
            fd.append("total", this.formData.total);
            fd.append("tax", this.formData.tax);
            fd.append("sum", this.formData.sum);
            fd.append("goods", JSON.stringify(this.formData.goods));
            fd.append("memo", this.formData.memo);
            fd.append("rids",this.upconfig.rids.join(","));
            //附件上传
            let fid = 0;
            this.upconfig.fileList.forEach(file => {
              if (file.raw) {
                fd.append("file" + fid, file.raw);
                fid++;
              }
            });

            this.$axiosUploader.post("api/admin/saleticket/update", fd).then(res => {
              if (res.status == 200 && res.data.code) {
                this.$message.success({
                  message: res.data.msg,
                  duration: 1500,
                  showClose: true
                });
                this.upconfig.imgList = res.data.attachlist;
                this.formData.attach=res.data.attachlist;
                this.dialogVisible = false;
                this.$emit("completeHandler",this.index,this.formData);
                this.$refs.upload.clearFiles();
              } else {
                this.$message.error({
                  message: res.data.msg,
                  duration: 1500,
                  showClose: true
                });
              }
            });

          }
        });
      },
      handleDelete(index, row) {

          this.formData.goods.splice(index, 1);
          this.handleRefreshBottomSum();

      },
      handleAdd() {
        this.formData.goods.push({
          id: -1,
          title: '',
          model: '',
          unit: '',
          count: 1,
          price: '0.000000000',
          total: 0,
          taxcode: '',
          taxname: '',
          rate: '0.13',
          fphm: '',
          fpdm:'',
          tax: 0,
        });
      },
      handleClientChanged(clientname) {
        var option = this.clients.filter(function(cur, index, a) {
          if (cur.title == clientname) {
            return cur;
          }
        })[0];
      }
    }
  }
</script>

<style scoped>
  .tablewraper {
    height: 300px;
  }
</style>
